import React, { memo, useCallback, useEffect, useRef, useState } from 'react'
import { useSelector, shallowEqual, useDispatch } from 'react-redux'

import { Carousel } from 'antd';
import { DiscoverWrapper, BannerLeft, BannerRight, BannerControl } from './style'

import { getTopBannerAction } from '../../store/actionCreators'

export default memo(function WYTopBanner() {
  const [currentIndex, setCurrentIndex] = useState(0)

  // shallowEqual浅层比较
  const { topBanners } = useSelector(state => ({
    // topBanners: state.get('recommend').get("topBanners")
    topBanners: state.getIn(["recommend", "topBanners"])
  }), shallowEqual)
  
  const caroRef = useRef()

  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(getTopBannerAction())
  }, [dispatch])
  // 函数作为参数传递，使用useCallback
  const beforeChange = useCallback((form, to) => {
    setTimeout(() => {
      setCurrentIndex(to)
    }, 0)
  }, [])

  const bgImage = topBanners[currentIndex] && (topBanners[currentIndex].imageUrl + "?imageView&blur=40x20")

  return (
    <DiscoverWrapper bgImage={bgImage}>
      <div className="banner wrap-v2">
        <BannerLeft>
          <Carousel effect="fade" autoplay ref={caroRef} beforeChange={beforeChange}>
            {
              topBanners.map((item, index) => {
                return (
                  <div className="banner-item" key={item.imageUrl}>
                    <img src={item.imageUrl} alt="not-defined"></img>
                  </div>
                )
              })
            }
          </Carousel>
        </BannerLeft>
        <BannerRight>
          <a href="https://music.163.com/#/download" target="_blank" rel="noopener noreferrer"> </a>
        </BannerRight>
        <BannerControl>
          <div className="btn-l btn" onClick={e => caroRef.current.prev()}></div>
          <div className="btn-r btn" onClick={e => caroRef.current.next()}></div>
        </BannerControl>
      </div>
    </DiscoverWrapper>
  )
})